/**
 * eventBus事件总线支持订阅、发送事件、取消订阅
 */
type EventHandler = (...args: any[]) => void;

export namespace EventBus {
    let events: Record<string, EventHandler[]> = {};

    export const subscribe = (eventName: string, handler: EventHandler) => {
        if (!events[eventName]) {
            events[eventName] = [];
        }
        events[eventName].push(handler);
    }
    export const unsubscribe = (eventName: string, handler: EventHandler) => {
        if (!events[eventName]) {
            return;
        }
        events[eventName] = events[eventName].filter((eventHandler) => eventHandler !== handler);
    }

    export const emit = (eventName: string, ...args: any[]) => {
        if (!events[eventName]) {
            return;
        }
        events[eventName].forEach((handler) => handler(...args));
    }
}